<script setup lang="ts">
import { ref, computed } from 'vue'

const color = ref('#3B82F6')

const rgb = computed(() => {
  const c = color.value.replace('#', '')
  const r = parseInt(c.substring(0, 2), 16)
  const g = parseInt(c.substring(2, 4), 16)
  const b = parseInt(c.substring(4, 6), 16)
  return `${r}, ${g}, ${b}`
})

const hsl = computed(() => {
  const c = color.value.replace('#', '')
  const r = parseInt(c.substring(0, 2), 16) / 255
  const g = parseInt(c.substring(2, 4), 16) / 255
  const b = parseInt(c.substring(4, 6), 16) / 255
  const max = Math.max(r, g, b), min = Math.min(r, g, b)
  let h = 0, s = 0
  const l = (max + min) / 2
  const d = max - min
  if (d !== 0) {
    s = d / (1 - Math.abs(2 * l - 1))
    switch (max) {
      case r: h = ((g - b) / d) % 6; break
      case g: h = (b - r) / d + 2; break
      case b: h = (r - g) / d + 4; break
    }
    h *= 60
    if (h < 0) h += 360
  }
  return `${Math.round(h)}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%`
})

async function copy(text: string) {
  try {
    await navigator.clipboard.writeText(text)
    alert('已复制到剪贴板')
  } catch {
    alert('复制失败，请手动复制')
  }
}
</script>

<template>
  <div class="space-y-4">
    <div class="flex items-center gap-4">
      <input type="color" v-model="color" />
      <div class="w-10 h-10 rounded border border-gray-300" :style="{ background: color }"></div>
    </div>
    <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
      <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
        <p class="text-sm text-gray-500 dark:text-gray-400">HEX</p>
        <div class="flex items-center gap-2 mt-1">
          <code class="font-mono">{{ color }}</code>
          <button class="px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded" @click="copy(color)">复制</button>
        </div>
      </div>
      <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
        <p class="text-sm text-gray-500 dark:text-gray-400">RGB</p>
        <div class="flex items-center gap-2 mt-1">
          <code class="font-mono">rgb({{ rgb }})</code>
          <button class="px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded" @click="copy('rgb(' + rgb + ')')">复制</button>
        </div>
      </div>
      <div class="bg-gray-50 dark:bg-gray-700 p-4 rounded-lg">
        <p class="text-sm text-gray-500 dark:text-gray-400">HSL</p>
        <div class="flex items-center gap-2 mt-1">
          <code class="font-mono">hsl({{ hsl }})</code>
          <button class="px-2 py-1 bg-gray-200 dark:bg-gray-700 rounded" @click="copy('hsl(' + hsl + ')')">复制</button>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped></style>